package com.bicon.life.core.base.common.utils;

import com.bicon.life.core.base.common.entity.BaseResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * HTTP请求工具类
 */
public class HttpUtil {
    /**
     * 发送GET请求
     * @param url 目的地址
     * @param charset 编码字符集
     * @return 远程响应结果
     */
    public static String sendGet(String url, String charset) throws IOException {
        String result = null;
        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     * @param url 目的地址
     * @param map 请求参数
     * @param charset 编码字符集
     * @return 远程响应结果
     */
    public static String sendPost(String url, Map<String, String> map, String charset) throws IOException {
        String result = null;
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator
                    .next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, charset);
        httpPost.setEntity(uefEntity);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
        return result;
    }

    /**
     * 获取完整url带参数
     * */
    public static String getFullUrl(HttpServletRequest request){
        String url = request.getRequestURL().toString();
        String fullUrl = url;
        String paramUrl = "";
        Map<String, String[]> map = request.getParameterMap();
        if(map != null){
            if(!map.isEmpty()){
                Set<Map.Entry<String, String[]>> set = map.entrySet();
                Iterator<Map.Entry<String, String[]>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String[]> entry = it.next();
                    paramUrl = paramUrl+"&"+entry.getKey()+"=";
                    String value = "";
                    for (String v : entry.getValue()) {
                        value = value+v;
                    }
                    paramUrl = paramUrl+value;
                }
                fullUrl = fullUrl + "?" + paramUrl.replaceFirst("&", "");
            }
        }
        return fullUrl;
    }

    /**
     * 获取请求中参数
     * */
    public static Map<String, String[]> getParamMap(HttpServletRequest request){
        Map<String, String[]> map = request.getParameterMap();
        if(map != null){
            if(!map.isEmpty()){
                Set<Map.Entry<String, String[]>> set = map.entrySet();
                Iterator<Map.Entry<String, String[]>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String[]> entry = it.next();
                    String value = "";
                    for (String v : entry.getValue()) {
                        value = value+v;
                    }
                }
            }
        }
        return map;
    }

    /**
     * 获取真实ip地址
     * @param request
     * @return
     */
    public static String getRemoteHost(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }


    /**
     * 输出结果
     * @param response
     * @param result
     */
    public static void printFailMessage(HttpServletResponse response, BaseResult result){
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(JsonUtil.toJson(result));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out != null){
                out.close();
            }
        }
    }
}
